<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>💬 智能故事生成系统 - 修复版</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Microsoft YaHei', sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }
        
        .container {
            max-width: 1600px;
            margin: 0 auto;
        }
        
        .header {
            background: white;
            padding: 30px;
            border-radius: 20px;
            box-shadow: 0 10px 40px rgba(0,0,0,0.2);
            margin-bottom: 30px;
            text-align: center;
        }
        
        .header h1 {
            font-size: 2.5em;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            margin-bottom: 10px;
        }
        
        .mode-selector {
            display: flex;
            gap: 20px;
            justify-content: center;
            margin-bottom: 30px;
            flex-wrap: wrap;
        }
        
        .mode-card {
            background: white;
            padding: 25px;
            border-radius: 15px;
            cursor: pointer;
            transition: all 0.3s;
            border: 3px solid #e0e0e0;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
            text-align: center;
            flex: 1;
            min-width: 200px;
        }
        
        .mode-card:hover {
            border-color: #667eea;
            transform: translateY(-5px);
            box-shadow: 0 10px 25px rgba(102, 126, 234, 0.3);
        }
        
        .mode-card.active {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-color: #667eea;
        }
        
        .main-layout {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
        }
        
        .card {
            background: white;
            border-radius: 20px;
            padding: 30px;
            box-shadow: 0 10px 40px rgba(0,0,0,0.1);
        }
        
        .card h2 {
            color: #2c3e50;
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 3px solid #667eea;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
        /* 文本模式样式 */
        .text-card {
            height: 700px;
            display: flex;
            flex-direction: column;
        }
        
        .config-bar {
            display: flex;
            gap: 15px;
            padding: 15px;
            background: #f8f9ff;
            border-radius: 12px;
            margin-bottom: 15px;
            align-items: center;
        }
        
        .config-item {
            display: flex;
            align-items: center;
            gap: 8px;
        }
        
        .config-item label {
            font-weight: 600;
            color: #555;
            font-size: 0.9em;
        }
        
        .config-item input {
            width: 80px;
            padding: 8px 12px;
            border: 2px solid #e0e0e0;
            border-radius: 8px;
            text-align: center;
            font-weight: 600;
        }
        
        .text-input-container {
            flex: 1;
            display: flex;
            flex-direction: column;
            gap: 12px;
        }
        
        .file-upload {
            border: 3px dashed #667eea;
            border-radius: 15px;
            padding: 20px;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s;
            background: #f8f9ff;
        }
        
        .file-upload:hover {
            background: #eef0ff;
            border-color: #764ba2;
        }
        
        .file-upload input {
            display: none;
        }
        
        #textInput {
            flex: 1;
            padding: 15px;
            border: 2px solid #e0e0e0;
            border-radius: 12px;
            resize: none;
            font-size: 0.95em;
            font-family: inherit;
        }
        
        .text-generate-btn {
            width: 100%;
            padding: 15px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            border-radius: 12px;
            font-size: 1.1em;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s;
        }
        
        .text-generate-btn:hover:not(:disabled) {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
        }
        
        .text-generate-btn:disabled {
            opacity: 0.6;
            cursor: not-allowed;
        }
        
        /* 对话模式样式 */
        .chat-card {
            height: 700px;
            display: flex;
            flex-direction: column;
        }
        
        .status-bar {
            display: flex;
            align-items: center;
            gap: 10px;
            padding: 12px 18px;
            background: linear-gradient(135deg, #f8f9ff 0%, #fff 100%);
            border-radius: 12px;
            margin-bottom: 15px;
            border-left: 4px solid #667eea;
        }
        
        .status-badge {
            padding: 6px 14px;
            border-radius: 20px;
            font-size: 0.85em;
            font-weight: 600;
        }
        
        .status-chatting { background: #fff3cd; color: #856404; }
        .status-generating { background: #d1ecf1; color: #0c5460; }
        .status-completed { background: #d4edda; color: #155724; }
        
        .chat-messages {
            flex: 1;
            overflow-y: auto;
            padding: 20px;
            background: #f8f9ff;
            border-radius: 15px;
            margin-bottom: 15px;
        }
        
        .message {
            margin-bottom: 15px;
            padding: 12px 18px;
            border-radius: 12px;
            max-width: 80%;
            animation: slideIn 0.3s ease;
            word-wrap: break-word;
        }
        
        .message.user {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            margin-left: auto;
            box-shadow: 0 2px 8px rgba(102, 126, 234, 0.3);
        }
        
        .message.assistant {
            background: white;
            color: #333;
            border: 2px solid #e0e0e0;
            box-shadow: 0 2px 8px rgba(0,0,0,0.05);
        }
        
        .quick-suggestions {
            display: flex;
            gap: 8px;
            margin-bottom: 12px;
            flex-wrap: wrap;
        }
        
        .suggestion-btn {
            padding: 8px 16px;
            background: #f0f0f0;
            border: 2px solid #e0e0e0;
            border-radius: 20px;
            font-size: 0.9em;
            cursor: pointer;
            transition: all 0.3s;
            color: #555;
        }
        
        .suggestion-btn:hover {
            background: #667eea;
            color: white;
            border-color: #667eea;
            transform: translateY(-2px);
        }
        
        .chat-input-area {
            display: flex;
            gap: 10px;
        }
        
        .chat-input-area input {
            flex: 1;
            padding: 12px 18px;
            border: 2px solid #e0e0e0;
            border-radius: 12px;
            font-size: 0.95em;
        }
        
        .chat-input-area button {
            padding: 12px 24px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            border-radius: 12px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s;
        }
        
        .chat-input-area button:hover:not(:disabled) {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
        }
        
        .chat-input-area button:disabled {
            opacity: 0.6;
            cursor: not-allowed;
        }
        
        /* 内容显示区域 */
        .content-card {
            max-height: 700px;
            overflow-y: auto;
        }
        
        .empty-state {
            text-align: center;
            padding: 60px 20px;
            color: #999;
        }
        
        .empty-state svg {
            width: 120px;
            height: 120px;
            margin-bottom: 20px;
            opacity: 0.3;
        }
        
        .story-page {
            background: linear-gradient(135deg, #f8f9ff 0%, #fff 100%);
            padding: 25px;
            margin-bottom: 20px;
            border-radius: 15px;
            border-left: 5px solid #667eea;
            box-shadow: 0 3px 10px rgba(0,0,0,0.05);
            position: relative;
            transition: all 0.3s;
        }
        
        .story-page:hover {
            box-shadow: 0 5px 20px rgba(102, 126, 234, 0.15);
            transform: translateX(5px);
        }
        
        .story-page h3 {
            color: #667eea;
            margin-bottom: 12px;
            font-size: 1.2em;
        }
        
        .page-content {
            color: #333;
            line-height: 1.8;
            font-size: 1em;
        }
        
        .page-actions {
            position: absolute;
            top: 15px;
            right: 15px;
        }
        
        .page-edit-btn {
            padding: 6px 12px;
            background: #fff;
            border: 2px solid #667eea;
            color: #667eea;
            border-radius: 8px;
            cursor: pointer;
            font-size: 0.85em;
            font-weight: 600;
            transition: all 0.3s;
        }
        
        .page-edit-btn:hover {
            background: #667eea;
            color: white;
        }
        
        .progress-container {
            background: #f8f9ff;
            padding: 20px;
            border-radius: 15px;
            margin-bottom: 20px;
            display: none;
        }
        
        .progress-bar {
            width: 100%;
            height: 30px;
            background: #e0e0e0;
            border-radius: 15px;
            overflow: hidden;
            margin-bottom: 10px;
        }
        
        .progress-fill {
            height: 100%;
            background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
            transition: width 0.3s;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-weight: 600;
            font-size: 0.85em;
        }
        
        .progress-text {
            text-align: center;
            color: #555;
            font-size: 0.9em;
        }
        
        .action-buttons {
            display: none;
            gap: 12px;
            margin-bottom: 20px;
        }
        
        .action-btn {
            flex: 1;
            padding: 14px;
            background: white;
            border: 3px solid #667eea;
            color: #667eea;
            border-radius: 12px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s;
            font-size: 0.95em;
        }
        
        .action-btn:hover:not(:disabled) {
            background: #667eea;
            color: white;
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(102, 126, 234, 0.3);
        }
        
        .action-btn:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }
        
        .images-container {
            display: none;
        }
        
        .image-item {
            margin-bottom: 20px;
            background: linear-gradient(135deg, #f8f9ff 0%, #fff 100%);
            padding: 20px;
            border-radius: 15px;
            border: 2px solid #e0e0e0;
        }
        
        .image-item h4 {
            color: #667eea;
            margin-bottom: 15px;
        }
        
        .image-item img {
            width: 100%;
            border-radius: 12px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }
        
        .video-container {
            display: none;
            margin-bottom: 20px;
        }
        
        .video-container h3 {
            color: #667eea;
            margin-bottom: 15px;
        }
        
        .video-container video {
            width: 100%;
            border-radius: 15px;
            box-shadow: 0 5px 20px rgba(0,0,0,0.15);
        }
        
        .video-download {
            display: inline-block;
            margin-top: 12px;
            padding: 10px 20px;
            background: #667eea;
            color: white;
            text-decoration: none;
            border-radius: 8px;
            font-weight: 600;
            transition: all 0.3s;
        }
        
        .video-download:hover {
            background: #764ba2;
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(102, 126, 234, 0.3);
        }
        
        /* 编辑模态框 */
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.5);
            z-index: 1000;
            align-items: center;
            justify-content: center;
        }
        
        .modal.show {
            display: flex;
        }
        
        .modal-content {
            background: white;
            padding: 30px;
            border-radius: 20px;
            max-width: 600px;
            width: 90%;
            max-height: 80vh;
            overflow-y: auto;
        }
        
        .modal-content h3 {
            color: #667eea;
            margin-bottom: 20px;
        }
        
        .modal-section {
            margin-bottom: 20px;
        }
        
        .modal-section label {
            display: block;
            font-weight: 600;
            margin-bottom: 8px;
            color: #555;
        }
        
        .modal-section textarea {
            width: 100%;
            padding: 12px;
            border: 2px solid #e0e0e0;
            border-radius: 8px;
            resize: vertical;
            font-family: inherit;
            min-height: 100px;
        }
        
        .modal-buttons {
            display: flex;
            gap: 12px;
            margin-top: 20px;
        }
        
        .modal-btn {
            flex: 1;
            padding: 12px;
            border-radius: 8px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s;
        }
        
        .modal-btn-primary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
        }
        
        .modal-btn-secondary {
            background: white;
            color: #667eea;
            border: 2px solid #667eea;
        }
        
        .modal-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(0,0,0,0.2);
        }
        
        @keyframes slideIn {
            from {
                opacity: 0;
                transform: translateY(10px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
        
        @keyframes typing {
            0%, 60%, 100% { transform: translateY(0); }
            30% { transform: translateY(-10px); }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>✨ 智能故事生成系统</h1>
            <p style="color: #666;">选择您喜欢的创作方式，开启奇幻故事之旅</p>
        </div>
        
        <div class="mode-selector">
            <div class="mode-card active" onclick="switchMode('chat')">
                <h3 style="font-size: 2em; margin-bottom: 10px;">💬</h3>
                <h3>对话模式</h3>
                <p style="color: #888; margin-top: 8px;">通过自然对话创作故事</p>
            </div>
            <div class="mode-card" onclick="switchMode('text')">
                <h3 style="font-size: 2em; margin-bottom: 10px;">✍️</h3>
                <h3>文本模式</h3>
                <p style="color: #888; margin-top: 8px;">输入文本或上传文件生成</p>
            </div>
        </div>
        
        <div class="main-layout">
            <!-- 左侧输入区域 -->
            <div>
                <!-- 对话模式 -->
                <div id="chatMode" class="card chat-card">
                    <h2>💬 对话创作</h2>
                    
                    <div class="config-bar">
                        <div class="config-item">
                            <label>📄 目标页数:</label>
                            <input type="number" id="chatTargetPages" value="2" min="2" max="20">
                        </div>
                    </div>
                    
                    <div class="status-bar">
                        <span class="status-badge status-chatting" id="statusBadge">💬 对话中</span>
                        <span id="statusText" style="color: #666;">和我聊聊您想要的故事...</span>
                    </div>
                    
                    <div class="chat-messages" id="chatMessages">
                        <!-- Messages will be added here -->
                    </div>
                    
                    <div class="quick-suggestions">
                        <button class="suggestion-btn" onclick="quickSend('我想要一个关于勇敢小猫的冒险故事')">
                            🐱 勇敢小猫
                        </button>
                        <button class="suggestion-btn" onclick="quickSend('创作一个太空探险的故事')">
                            🚀 太空探险
                        </button>
                        <button class="suggestion-btn" onclick="quickSend('讲一个友谊的故事')">
                            🤝 友谊故事
                        </button>
                    </div>
                    
                    <div class="chat-input-area">
                        <input type="text" id="chatInput" placeholder="输入您的想法..." 
                               onkeypress="if(event.key==='Enter') sendMessage()">
                        <button id="sendBtn" onclick="sendMessage()">发送</button>
                    </div>
                </div>
                
                <!-- 文本模式 -->
                <div id="textMode" class="card text-card" style="display: none;">
                    <h2>✍️ 文本输入</h2>
                    
                    <div class="config-bar">
                        <div class="config-item">
                            <label>📄 目标页数:</label>
                            <input type="number" id="textTargetPages" value="2" min="2" max="20">
                        </div>
                    </div>
                    
                    <div class="text-input-container">
                        <div class="file-upload" onclick="document.getElementById('fileInput').click()">
                            <p style="font-weight: 600; margin-bottom: 8px;">📁 选择文件</p>
                            <p style="font-size: 0.9em; color: #888;">已选择: <span id="fileName">example_novel.pdf (1179.28 KB)</span></p>
                            <input type="file" id="fileInput" accept=".txt,.pdf,.docx" onchange="handleFileSelect(event)">
                        </div>
                        
                        <textarea id="textInput" placeholder="或直接在此输入故事的关键要素...&#10;&#10;例如:&#10;- 主题: 勇气与友谊&#10;- 主角: 一只勇敢的小老鼠&#10;- 场景: 神秘的森林&#10;- 目标: 寻找失落的宝藏">%PDF-1.7
%����
1 0 obj
&lt;&lt;/Type/Catalog/Version/1.7/Pages 3 0 R/Outlines 2 0 R/Metadata 86 0 R&gt;&gt;
endobj
2 0 obj
&lt;&lt;/Type/Outlines&gt;&gt;
endobj
3 0 obj
&lt;&lt;/Type/Pages/Kids[8 0 R 18 0 R 24 0 R 30 0 R 36 0 R 42 0 R 48 0 R 54 0 R 60 0 R 66 0 R 72 0 R 78 0 R]/Count 12&gt;&gt;
endobj
4 0 obj
&lt;&lt;/Author()/CreationDate(D:20251114105910+08'00')/ModDate(D:20251114105914+08'00')/Producer(Aspose.PDF for .NET 20.3)/Subject()/Title()/Creator(Aspose Ltd.)&gt;&gt;
endobj</textarea>
                        
                        <button class="text-generate-btn" onclick="generateFromText()">
                            🎨 生成故事
                        </button>
                    </div>
                </div>
            </div>
            
            <!-- 右侧内容区域 -->
            <div class="card content-card">
                <h2>🌸 生成内容</h2>
                
                <div id="progressContainer" class="progress-container">
                    <div class="progress-bar">
                        <div class="progress-fill" id="progressFill" style="width: 0%">
                            <span id="progressPercent">0%</span>
                        </div>
                    </div>
                    <div class="progress-text" id="progressText">准备中...</div>
                </div>
                
                <div id="actionButtons" class="action-buttons">
                    <button class="action-btn" id="generateImagesBtn" onclick="generateImages()">
                        🖼️ 生成配图
                    </button>
                    <button class="action-btn" id="composeVideoBtn" onclick="composeVideo()" disabled>
                        🎬 合成视频
                    </button>
                </div>
                
                <div id="emptyState" class="empty-state">
                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor">
                        <path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-5 14H7v-2h7v2zm3-4H7v-2h10v2zm0-4H7V7h10v2z"/>
                    </svg>
                    <h3>开始创作您的故事</h3>
                    <p>选择一种模式开始创作</p>
                </div>
                
                <div id="storyPages" style="display: none;">
                    <!-- Story pages will be added here -->
                </div>
                
                <div id="videoContainer" class="video-container">
                    <h3>📺 生成的视频</h3>
                    <video id="videoPlayer" controls></video>
                    <a href="#" id="videoDownload" class="video-download" download>⬇️ 下载视频</a>
                </div>
                
                <div id="imagesContainer" class="images-container">
                    <!-- Images will be added here -->
                </div>
            </div>
        </div>
    </div>
    
    <!-- 编辑页面模态框 -->
    <div id="editModal" class="modal">
        <div class="modal-content">
            <h3>✏️ 编辑第 <span id="editPageNumber"></span> 页</h3>
            
            <div class="modal-section">
                <label>当前内容:</label>
                <div style="padding: 12px; background: #f8f9ff; border-radius: 8px; margin-bottom: 15px;">
                    <p id="currentPageContent" style="color: #333; line-height: 1.6;"></p>
                </div>
            </div>
            
            <div class="modal-section">
                <label>修改建议 (可选):</label>
                <textarea id="editFeedback" placeholder="例如: 让这一页更有趣一些，加入更多细节描写..."></textarea>
            </div>
            
            <div class="modal-buttons">
                <button class="modal-btn modal-btn-secondary" onclick="closeEditModal()">
                    取消
                </button>
                <button class="modal-btn modal-btn-primary" onclick="confirmRegeneratePage()">
                    重新生成
                </button>
            </div>
        </div>
    </div>
    
    <script>
        const API_BASE = 'http://127.0.0.1:5000/api';
        
        // 全局状态
        const state = {
            mode: 'chat',
            sessionId: null,
            isWaiting: false,
            storyPages: [],
            pollInterval: null,
            editingPageIndex: null,
            imagesGenerated: false
        };
        
        // 模式切换
        async function switchMode(mode) {
            state.mode = mode;
            
            document.querySelectorAll('.mode-card').forEach(card => {
                card.classList.remove('active');
            });
            event.target.closest('.mode-card').classList.add('active');
            
            // ✅ 改进: 总是创建新的会话以避免类型混淆
            if (mode === 'chat') {
                document.getElementById('chatMode').style.display = 'flex';
                document.getElementById('textMode').style.display = 'none';
                // 创建新的对话会话
                await initChat();
            } else {
                document.getElementById('chatMode').style.display = 'none';
                document.getElementById('textMode').style.display = 'flex';
                // 创建新的文本会话
                await initText();
            }
            
            // 重置内容显示
            document.getElementById('emptyState').style.display = 'block';
            document.getElementById('storyPages').style.display = 'none';
            document.getElementById('actionButtons').style.display = 'none';
            document.getElementById('videoContainer').style.display = 'none';
            document.getElementById('imagesContainer').style.display = 'none';
        }
        
        // 初始化对话模式
        async function initChat() {
            console.log('🎬 初始化对话模式...');
            try {
                const targetPages = parseInt(document.getElementById('chatTargetPages').value) || 2;
                const response = await fetch(`${API_BASE}/start-chat-session`, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ config: { target_pages: targetPages } })
                });
                
                const data = await response.json();
                if (data.success) {
                    state.sessionId = data.session_id;
                    console.log('✅ 对话会话创建成功:', state.sessionId);
                    
                    const messagesDiv = document.getElementById('chatMessages');
                    messagesDiv.innerHTML = '';
                    addMessage('assistant', data.welcome_message);
                }
            } catch (error) {
                console.error('❌ 初始化失败:', error);
            }
        }
        
        // 初始化文本模式
        async function initText() {
            console.log('📝 初始化文本模式...');
            try {
                const response = await fetch(`${API_BASE}/start-direct-session`, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' }
                });
                
                const data = await response.json();
                if (data.success) {
                    state.sessionId = data.session_id;
                    console.log('✅ 文本会话创建成功:', state.sessionId);
                }
            } catch (error) {
                console.error('❌ 初始化失败:', error);
            }
        }
        
        // 对话模式 - 发送消息
        async function sendMessage() {
            const input = document.getElementById('chatInput');
            const message = input.value.trim();
            
            if (!message || state.isWaiting) {
                return;
            }
            
            // ✅ 关键修复: 确保会话已初始化
            if (!state.sessionId) {
                console.log('⚠️ 会话未初始化,正在创建...');
                await initChat();
                // 等待一下确保会话创建完成
                if (!state.sessionId) {
                    addMessage('assistant', '会话初始化失败,请刷新页面重试');
                    return;
                }
            }
            
            addMessage('user', message);
            input.value = '';
            showTyping();
            state.isWaiting = true;
            disableInput(true);
            
            try {
                const targetPages = parseInt(document.getElementById('chatTargetPages').value);
                console.log('📡 发送请求:', { sessionId: state.sessionId, targetPages });
                
                const response = await fetch(`${API_BASE}/chat`, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        session_id: state.sessionId,
                        message: message,
                        target_pages: targetPages
                    })
                });
                
                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}`);
                }
                
                const data = await response.json();
                console.log('📥 收到响应:', data);
                
                removeTyping();
                state.isWaiting = false;
                disableInput(false);
                
                if (data.success) {
                    addMessage('assistant', data.response);
                    if (data.stage === 'preparing') {
                        updateStatus('generating', '生成中');
                        await generateStory(data.story_params);
                    }
                } else {
                    addMessage('assistant', '抱歉,发生了错误: ' + data.error);
                }
            } catch (error) {
                removeTyping();
                state.isWaiting = false;
                disableInput(false);
                console.error('❌ 发送失败:', error);
                addMessage('assistant', `抱歉,发生了错误: ${error.message}\n\n请重试。`);
            }
        }
        
        function quickSend(message) {
            const input = document.getElementById('chatInput');
            if (input) {
                input.value = message;
                sendMessage();
            }
        }
        
        // 生成故事
        async function generateStory(storyParams) {
            console.log('🎨 开始生成故事:', storyParams);
            
            document.getElementById('emptyState').style.display = 'none';
            document.getElementById('storyPages').style.display = 'block';
            document.getElementById('progressContainer').style.display = 'block';
            updateProgress(30, '正在使用AI创作故事...');
            
            try {
                const response = await fetch(`${API_BASE}/generate-from-chat`, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        session_id: state.sessionId,
                        story_params: storyParams
                    })
                });
                
                const data = await response.json();
                console.log('✅ 生成请求已发送:', data);
                
                if (data.success) {
                    startPolling();
                } else {
                    throw new Error(data.error || '生成失败');
                }
            } catch (error) {
                console.error('❌ 生成失败:', error);
                updateProgress(0, '生成失败: ' + error.message);
                document.getElementById('progressContainer').style.display = 'none';
                state.isWaiting = false;
                disableInput(false);
            }
        }
        
        // 文本生成 - **修复后的版本**
        async function generateFromText() {
            const text = document.getElementById('textInput').value.trim();
            const targetPages = parseInt(document.getElementById('textTargetPages').value);
            
            if (!text) {
                alert('请输入故事描述或上传文件');
                return;
            }
            
            console.log('📝 从文本生成故事:', { length: text.length, targetPages });
            
            // 确保有会话ID
            if (!state.sessionId) {
                await initText();
            }
            
            document.getElementById('emptyState').style.display = 'none';
            document.getElementById('storyPages').style.display = 'block';
            document.getElementById('progressContainer').style.display = 'block';
            updateProgress(10, '正在生成故事...');
            
            try {
                const response = await fetch(`${API_BASE}/generate-from-text`, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        session_id: state.sessionId,
                        text: text,
                        target_pages: targetPages
                    })
                });
                
                const data = await response.json();
                console.log('✅ 文本生成请求已发送:', data);
                
                if (data.success) {
                    startPolling();
                } else {
                    throw new Error(data.error || '生成失败');
                }
            } catch (error) {
                console.error('❌ 生成失败:', error);
                updateProgress(0, '生成失败: ' + error.message);
                document.getElementById('progressContainer').style.display = 'none';
            }
        }
        
        // 轮询状态
        function startPolling() {
            if (state.pollInterval) {
                clearInterval(state.pollInterval);
            }
            
            let pollAttempts = 0;
            const maxPollAttempts = 300;
            
            console.log('🔄 开始轮询状态...');
            
            state.pollInterval = setInterval(async () => {
                pollAttempts++;
                if (pollAttempts > maxPollAttempts) {
                    clearInterval(state.pollInterval);
                    state.pollInterval = null;
                    console.error('❌ 轮询超时');
                    alert('生成超时,请检查后台日志');
                    document.getElementById('progressContainer').style.display = 'none';
                    return;
                }
                
                try {
                    const response = await fetch(`${API_BASE}/chat-session-status/${state.sessionId}`);
                    if (!response.ok) return;
                    
                    const data = await response.json();
                    if (!data.success) return;
                    
                    updateProgress(data.progress, data.status_message);
                    
                    if (data.stage === 'completed' && data.has_story) {
                        clearInterval(state.pollInterval);
                        state.pollInterval = null;
                        
                        console.log('✅ 故事生成完成:', data.story_pages.length, '页');
                        
                        state.storyPages = data.story_pages;
                        displayStory(data.story_pages);
                        
                        updateStatus('completed', '已完成');
                        if (state.mode === 'chat') {
                            addMessage('assistant', `✅ 故事创作完成!共 ${data.story_pages.length} 页。你可以点击每页右上角的 ✏️ 按钮进行局部调整。`);
                        }
                        
                        document.getElementById('progressContainer').style.display = 'none';
                        document.getElementById('actionButtons').style.display = 'flex';
                    } else if (data.stage === 'error') {
                        clearInterval(state.pollInterval);
                        state.pollInterval = null;
                        console.error('❌ 生成错误:', data.status_message);
                        updateProgress(0, '❌ ' + data.status_message);
                        document.getElementById('progressContainer').style.display = 'none';
                    }
                } catch (error) {
                    console.error('轮询错误:', error);
                }
            }, 2000);
        }
        
        // 显示故事
        function displayStory(pages) {
            const container = document.getElementById('storyPages');
            container.innerHTML = '';
            
            pages.forEach((page, index) => {
                const pageDiv = document.createElement('div');
                pageDiv.className = 'story-page';
                pageDiv.innerHTML = `
                    <div class="page-actions">
                        <button class="page-edit-btn" onclick="openEditModal(${index})">
                            ✏️ 编辑
                        </button>
                    </div>
                    <h3>📄 第 ${index + 1} 页</h3>
                    <div class="page-content">${page}</div>
                `;
                container.appendChild(pageDiv);
            });
        }
        
        // 打开编辑对话框
        function openEditModal(pageIndex) {
            state.editingPageIndex = pageIndex;
            document.getElementById('editPageNumber').textContent = pageIndex + 1;
            document.getElementById('currentPageContent').textContent = state.storyPages[pageIndex];
            document.getElementById('editFeedback').value = '';
            document.getElementById('editModal').classList.add('show');
        }
        
        // 关闭编辑对话框
        function closeEditModal() {
            document.getElementById('editModal').classList.remove('show');
            state.editingPageIndex = null;
        }
        
        // 确认重新生成页面
        async function confirmRegeneratePage() {
            if (state.editingPageIndex === null) return;
            
            const feedback = document.getElementById('editFeedback').value.trim();
            const pageIndex = state.editingPageIndex;
            
            console.log('🔄 重新生成页面:', { pageIndex, feedback });
            
            closeEditModal();
            
            document.getElementById('progressContainer').style.display = 'block';
            updateProgress(30, `正在重新生成第 ${pageIndex + 1} 页...`);
            
            try {
                const response = await fetch(`${API_BASE}/regenerate-page`, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        session_id: state.sessionId,
                        page_index: pageIndex,
                        feedback: feedback
                    })
                });
                
                const data = await response.json();
                if (data.success) {
                    let pollAttempts = 0;
                    const maxPollAttempts = 60;
                    
                    const pollRegenerate = setInterval(async () => {
                        pollAttempts++;
                        if (pollAttempts > maxPollAttempts) {
                            clearInterval(pollRegenerate);
                            alert('重新生成超时');
                            document.getElementById('progressContainer').style.display = 'none';
                            return;
                        }
                        
                        try {
                            const statusRes = await fetch(`${API_BASE}/chat-session-status/${state.sessionId}`);
                            if (!statusRes.ok) return;
                            
                            const statusData = await statusRes.json();
                            if (!statusData.success) return;
                            
                            updateProgress(statusData.progress, statusData.status_message);
                            
                            if (statusData.stage === 'completed' && statusData.status_message.includes('重新生成完成')) {
                                clearInterval(pollRegenerate);
                                
                                state.storyPages = statusData.story_pages;
                                displayStory(statusData.story_pages);
                                
                                document.getElementById('progressContainer').style.display = 'none';
                                
                                if (state.mode === 'chat') {
                                    addMessage('assistant', `✅ 第 ${pageIndex + 1} 页已重新生成!`);
                                }
                                
                                const pages = document.querySelectorAll('.story-page');
                                if (pages[pageIndex]) {
                                    pages[pageIndex].style.background = 'linear-gradient(135deg, #fff3cd 0%, #fff 100%)';
                                    setTimeout(() => {
                                        pages[pageIndex].style.background = 'linear-gradient(135deg, #f8f9ff 0%, #fff 100%)';
                                    }, 2000);
                                }
                            } else if (statusData.stage === 'error') {
                                clearInterval(pollRegenerate);
                                alert('重新生成失败: ' + statusData.status_message);
                                document.getElementById('progressContainer').style.display = 'none';
                            }
                        } catch (error) {
                            console.error('轮询错误:', error);
                        }
                    }, 2000);
                } else {
                    throw new Error(data.error || '请求失败');
                }
            } catch (error) {
                console.error('❌ 重新生成失败:', error);
                alert('重新生成失败: ' + error.message);
                document.getElementById('progressContainer').style.display = 'none';
            }
        }
        
        // 生成图片
        async function generateImages() {
            if (!state.sessionId || !state.storyPages || state.storyPages.length === 0) {
                alert('请先生成故事');
                return;
            }
            
            const btn = document.getElementById('generateImagesBtn');
            btn.disabled = true;
            btn.textContent = '⏳ 生成中...';
            
            updateStatus('generating', '生成配图中');
            document.getElementById('progressContainer').style.display = 'block';
            updateProgress(10, '正在准备...');
            
            try {
                const response = await fetch(`${API_BASE}/generate-images`, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ session_id: state.sessionId })
                });
                
                const data = await response.json();
                if (data.success) {
                    document.getElementById('imagesContainer').style.display = 'block';
                    document.getElementById('imagesContainer').innerHTML = '';
                    
                    let pollAttempts = 0;
                    const maxPollAttempts = 300;
                    
                    const pollImages = setInterval(async () => {
                        pollAttempts++;
                        if (pollAttempts > maxPollAttempts) {
                            clearInterval(pollImages);
                            alert('生成超时');
                            btn.disabled = false;
                            btn.textContent = '🖼️ 重试生成配图';
                            document.getElementById('progressContainer').style.display = 'none';
                            return;
                        }
                        
                        try {
                            const statusRes = await fetch(`${API_BASE}/chat-session-status/${state.sessionId}`);
                            if (!statusRes.ok) return;
                            
                            const statusData = await statusRes.json();
                            if (!statusData.success) return;
                            
                            updateProgress(statusData.progress, statusData.status_message);
                            
                            if (statusData.generated_images && statusData.generated_images.length > 0) {
                                displayNewImages(statusData.generated_images);
                            }
                            
                            if (statusData.stage === 'completed') {
                                clearInterval(pollImages);
                                document.getElementById('progressContainer').style.display = 'none';
                                
                                if (state.mode === 'chat') {
                                    addMessage('assistant', '✅ 配图生成完成!');
                                }
                                
                                state.imagesGenerated = true;
                                document.getElementById('composeVideoBtn').disabled = false;
                                btn.disabled = false;
                                btn.textContent = '🖼️ 重新生成配图';
                                updateStatus('completed', '已完成');
                            }
                        } catch (error) {
                            console.error('轮询错误:', error);
                        }
                    }, 2000);
                } else {
                    throw new Error(data.error || '生成失败');
                }
            } catch (error) {
                console.error('❌ 配图生成失败:', error);
                btn.disabled = false;
                btn.textContent = '🖼️ 生成配图';
                document.getElementById('progressContainer').style.display = 'none';
            }
        }
        
        function displayNewImages(images) {
            const container = document.getElementById('imagesContainer');
            images.forEach((img) => {
                if (!document.getElementById(`img-${img.index}`)) {
                    const imgDiv = document.createElement('div');
                    imgDiv.className = 'image-item';
                    imgDiv.id = `img-${img.index}`;
                    imgDiv.innerHTML = `
                        <h4>📸 第 ${img.index + 1} 页配图</h4>
                        <img src="${img.url}" alt="故事配图 ${img.index + 1}">
                    `;
                    container.appendChild(imgDiv);
                }
            });
        }
        
        // 合成视频
        async function composeVideo() {
            if (!state.sessionId) {
                alert('请先完成故事和配图生成');
                return;
            }
            
            const btn = document.getElementById('composeVideoBtn');
            btn.disabled = true;
            btn.textContent = '⏳ 合成中...';
            
            updateStatus('generating', '合成视频中');
            document.getElementById('progressContainer').style.display = 'block';
            updateProgress(10, '正在准备...');
            
            try {
                const response = await fetch(`${API_BASE}/compose-video`, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ session_id: state.sessionId })
                });
                
                const data = await response.json();
                if (data.success) {
                    let pollAttempts = 0;
                    const maxPollAttempts = 600;
                    
                    const pollVideo = setInterval(async () => {
                        pollAttempts++;
                        if (pollAttempts > maxPollAttempts) {
                            clearInterval(pollVideo);
                            alert('合成超时');
                            btn.disabled = false;
                            btn.textContent = '🎬 重试合成视频';
                            document.getElementById('progressContainer').style.display = 'none';
                            return;
                        }
                        
                        try {
                            const statusRes = await fetch(`${API_BASE}/chat-session-status/${state.sessionId}`);
                            if (!statusRes.ok) return;
                            
                            const statusData = await statusRes.json();
                            if (!statusData.success) return;
                            
                            updateProgress(statusData.progress, statusData.status_message);
                            
                            if (statusData.stage === 'completed' && statusData.status_message.includes('视频已保存')) {
                                clearInterval(pollVideo);
                                document.getElementById('progressContainer').style.display = 'none';
                                
                                displayVideo(state.sessionId);
                                
                                if (state.mode === 'chat') {
                                    addMessage('assistant', '🎉 视频合成完成!');
                                }
                                
                                btn.disabled = false;
                                btn.textContent = '🎬 重新合成视频';
                                updateStatus('completed', '全部完成');
                            }
                        } catch (error) {
                            console.error('轮询错误:', error);
                        }
                    }, 2000);
                } else {
                    throw new Error(data.error || '合成失败');
                }
            } catch (error) {
                console.error('❌ 视频合成失败:', error);
                btn.disabled = false;
                btn.textContent = '🎬 合成视频';
                document.getElementById('progressContainer').style.display = 'none';
            }
        }
        
        // 显示视频
        function displayVideo(sessionId) {
            const videoContainer = document.getElementById('videoContainer');
            const videoPlayer = document.getElementById('videoPlayer');
            const videoDownload = document.getElementById('videoDownload');
            
            const videoUrl = `${API_BASE}/video/${sessionId}`;
            videoPlayer.src = videoUrl;
            videoDownload.href = videoUrl;
            
            videoContainer.style.display = 'block';
            videoContainer.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
        }
        
        // UI辅助函数
        function addMessage(role, content) {
            const messagesDiv = document.getElementById('chatMessages');
            const messageDiv = document.createElement('div');
            messageDiv.className = `message ${role}`;
            messageDiv.textContent = content;
            messagesDiv.appendChild(messageDiv);
            messagesDiv.scrollTop = messagesDiv.scrollHeight;
        }
        
        function showTyping() {
            const messagesDiv = document.getElementById('chatMessages');
            const typingDiv = document.createElement('div');
            typingDiv.className = 'message assistant';
            typingDiv.id = 'typing-indicator';
            typingDiv.innerHTML = '<div style="display:inline-flex; gap:4px;"><span style="width:8px; height:8px; border-radius:50%; background:#667eea; animation:typing 1.4s infinite;"></span><span style="width:8px; height:8px; border-radius:50%; background:#667eea; animation:typing 1.4s 0.2s infinite;"></span><span style="width:8px; height:8px; border-radius:50%; background:#667eea; animation:typing 1.4s 0.4s infinite;"></span></div>';
            messagesDiv.appendChild(typingDiv);
            messagesDiv.scrollTop = messagesDiv.scrollHeight;
        }
        
        function removeTyping() {
            const typing = document.getElementById('typing-indicator');
            if (typing) typing.remove();
        }
        
        function updateStatus(stage, text) {
            const badge = document.getElementById('statusBadge');
            const statusText = document.getElementById('statusText');
            
            const statusMap = {
                'chatting': { text: '💬 对话中', class: 'status-chatting' },
                'generating': { text: '⏳ 生成中', class: 'status-generating' },
                'completed': { text: '✅ 已完成', class: 'status-completed' }
            };
            
            const status = statusMap[stage];
            if (status) {
                badge.textContent = status.text;
                badge.className = 'status-badge ' + status.class;
            }
            if (text) statusText.textContent = text;
        }
        
        function updateProgress(percent, text) {
            document.getElementById('progressFill').style.width = percent + '%';
            document.getElementById('progressPercent').textContent = percent + '%';
            document.getElementById('progressText').textContent = text || `生成中... ${percent}%`;
        }
        
        function disableInput(disabled) {
            const chatInput = document.getElementById('chatInput');
            const sendBtn = document.getElementById('sendBtn');
            
            if (chatInput) {
                chatInput.disabled = disabled;
            }
            if (sendBtn) {
                sendBtn.disabled = disabled;
            }
            
            console.log(disabled ? '🔒 输入已禁用' : '🔓 输入已启用');
        }
        
        // 文件处理
        function handleFileSelect(event) {
            const file = event.target.files[0];
            if (file) {
                document.getElementById('fileName').textContent = `${file.name} (${(file.size / 1024).toFixed(2)} KB)`;
                
                const reader = new FileReader();
                reader.onload = function(e) {
                    document.getElementById('textInput').value = e.target.result;
                };
                reader.readAsText(file);
            }
        }
        
        // 页面加载完成后初始化
        window.addEventListener('DOMContentLoaded', async () => {
            console.log('🎬 页面加载完成，开始初始化...');
            console.log('🔧 初始状态设置...');
            
            state.isWaiting = false;
            disableInput(false);
            
            // 切换到对话模式（会自动调用 initChat）
            await switchMode('chat');
        });
    </script>
</body>
</html>